package com.lagou;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 静态资源工具类
 */
public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     *
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * 读取静态资源文件输入流,通过输出流输出
     *
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int resourceSize = 0;
        while (resourceSize == 0) {
            resourceSize = inputStream.available();
        }

        //输入http请求头
        outputStream.write(HttpProtocolUtils.getHttpHeader200(resourceSize).getBytes());
        //读取内容输出
        long written = 0;//已经读取的内容长度
        int byteSize = 1024; //每次读取的长度

        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            if (written + byteSize > resourceSize) {
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            //读取到数组中
            inputStream.read(bytes);
            //写出
            outputStream.write(bytes);

            outputStream.flush();
            written += byteSize;
        }
    }
}
